package main

import (
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{} // 使用缺省选项

func home(w http.ResponseWriter, request *http.Request) {
	// fmt.Printf("请求=%v\n", request)
	w.Header().Add("X-Server", "magedu.com") // 响应头
	http.ServeFile(w, request, "index.html") // 响应的内容
}

func wsecho(w http.ResponseWriter, request *http.Request) {
	// fmt.Printf("请求=%v\n", request)
	//https://github.com/gorilla/websocket/blob/master/examples/echo/server.go/echo
	c, err := upgrader.Upgrade(w, request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		mt, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("recv: %s", message)
		err = c.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			break
		}
	}
}

func main() {
	// URL映射刀handler, handler函数2个参数一进一出
	http.HandleFunc("/", home)               // HTTP协议处理
	http.HandleFunc("/wsecho", wsecho)       // ws协议处理
	http.ListenAndServe("0.0.0.0:9999", nil) // http协议监听9999端口
}
